package cn.autumnorange.app.common.rpc.anntation;

import org.aopalliance.intercept.MethodInvocation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public abstract class AbstractAnnotationStrategy implements AnnotationStrategy {
  //  private Annotation annotation;
  /** 是否需要注解才执行注解策略逻辑方法 默认需要注解才能执行AnnotationStrategy */
  private boolean needAnnotation = true;
  //  @Override
  //  public void setAnnotation(Annotation annotation) {
  //    this.annotation = annotation;
  //  }

  //  @Override
  //  public Annotation getAnnotation() {
  //    return this.annotation;
  //  }
  @Override
  public Object annotationTargetHandle(String annotationName, MethodInvocation invocation)
      throws Throwable {
    AnnotationContext annotationContext = AnnotationContext.getAnnotationContext();
    Method method = invocation.getMethod();
    String methodName = annotationContext.getMethodAllMSG(method);
    String className = invocation.getMethod().getDeclaringClass().getName();
    // 校验注解待加到缓存中读取
    Annotation annotation =
        annotationContext.checkAnnotation(className, methodName, annotationName, true, true);
    AnnotationStrategy annotationStrategy = this;
    // 每次请求都需要获取当前注解信息线程获取在接口上的注解不能放到单例对象属性中并发时后一个线程会替换上个线程对象属性

    //必须要注解的情况和注解是不必要的情况
    if ((annotation != null && annotationStrategy.isNeedAnnotation())||!annotationStrategy.isNeedAnnotation()) {
      return this.annotationTargetHandle(invocation, annotation);
    } else {
      //    需要注解存在的情况但是注解无法获取到则执行业务代码 annotation == null &&annotationStrategy.isNeedAnnotation()
      return invocation.proceed();
    }
  }

  public boolean isNeedAnnotation() {
    return needAnnotation;
  }

  public void setNeedAnnotation(boolean needAnnotation) {
    this.needAnnotation = needAnnotation;
  }
}
